<template>
  <div class="content-panel">
    <!-- <div class="content-header"> -->
      <!-- <div class="header-title">表单内容</div> -->
      <!-- <div class="header-tip">拖拽或点击左侧组件进行表单设计</div> -->
    <!-- </div> -->
    
    <draggable
      class="container"
      :list="newList"
      group="form"
      item-key="id"
      animation="300"
      @add="dragDown"
      @end="dragEnd"
      @change="handleDragChange"
    >
      <template #item="{ element, index }">
        <div 
          @click="handleClick(element, index)" 
          :class="[
            'form-item',
            { 'active': selectFormItem && selectFormItem.id === element.id && showOperate },
            { 'error': element?.hasError === false }
          ]"
        >
          <div class="item-actions" v-show="selectFormItem && selectFormItem.id === element.id">
            <el-tooltip content="向上移动" placement="top" v-if="index !== 0">
              <el-button 
                class="move-btn"
                circle
                size="small"
                @click.stop="moveItem(index, 'up')"
              >
                <el-icon><ArrowUp /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="向下移动" placement="top" v-if="index !== newList.length - 1">
              <el-button
                class="move-btn"
                circle
                size="small"
                @click.stop="moveItem(index, 'down')"
              >
                <el-icon><ArrowDown /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="复制组件" placement="top">
              <el-button
                class="copy-btn"
                circle
                size="small"
                @click.stop="copyItem(element)"
              >
                <el-icon><CopyDocument /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="删除组件" placement="top">
              <el-button 
                class="delete-btn"
                type="danger" 
                circle
                size="small"
                @click.stop="removeAt(index)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </el-tooltip>
          </div>
          <div class="item-content">
            <div class="drag-handle">
              <el-icon><DArrowRight /></el-icon>
            </div>
            <div class="component-label">
              <el-tag size="small" :type="element.type === 'layout' ? 'warning' : 'info'">
                {{ element.name }}
              </el-tag>
            </div>
            <template v-if="element.type === 'grid'">
              <div class="grid-container">
                <el-row 
                  :gutter="element.options.gutter"
                  :justify="element.options.justify"
                  :align="element.options.align"
                >
                  <el-col 
                    v-for="(col, colIndex) in element.options.columns"
                    :key="colIndex"
                    :span="col.span"
                  >
                    <draggable
                      class="grid-col-container"
                      :list="col.list"
                      group="form"
                      item-key="id"
                      animation="300"
                      @add="(e) => handleColAdd(e, colIndex, element)"
                      @end="dragEnd"
                      @change="(e) => handleColChange(e, colIndex, element)"
                    >
                      <template #item="{ element: colElement, index: colElementIndex }">
                        <div 
                          class="grid-item"
                          @click.stop="handleClick(colElement, colElementIndex)"
                        >
                          <element-comps :element="colElement" />
                        </div>
                      </template>
                      <template #footer>
                        <div class="grid-placeholder">
                          <el-icon><Plus /></el-icon>
                          <span>拖拽组件到这里</span>
                        </div>
                      </template>
                    </draggable>
                  </el-col>
                </el-row>
              </div>
            </template>
            <template v-else-if="element.type === 'card'">
              <div class="card-container">
                <div class="card-header" v-if="element.options.showHeader">
                  {{ element.options.title }}
                </div>
                <draggable
                  class="card-content"
                  :list="element.options.list"
                  group="form"
                  item-key="id"
                  animation="300"
                  @add="(e) => handleCardAdd(e, element)"
                  @end="dragEnd"
                  @change="(e) => handleCardChange(e, element)"
                >
                  <template #item="{ element: cardElement, index: cardElementIndex }">
                    <div 
                      class="card-item"
                      @click.stop="handleClick(cardElement, cardElementIndex)"
                    >
                      <element-comps :element="cardElement" />
                    </div>
                  </template>
                  <template #footer>
                    <div class="card-placeholder">
                      <el-icon><Plus /></el-icon>
                      <span>拖拽组件到这里</span>
                    </div>
                  </template>
                </draggable>
              </div>
            </template>
            <template v-else-if="element.type === 'dynamic-form'">
              <div class="dynamic-form-container">
                <!-- 表头 -->
                <div v-if="element.options.showHeader" class="dynamic-form-header">
                  {{ element.options.title }}
                </div>
                
                <!-- 表格 -->
                <div class="dynamic-form-content">
                  <!-- 列配置预览 -->
                  <div class="dynamic-form-preview">
                    <div class="preview-header">
                      <span class="preview-title">列配置</span>
                    </div>
                    <div class="preview-columns">
                      <template v-if="element.options.columns.length > 0">
                        <div 
                          v-for="col in element.options.columns" 
                          :key="col.prop"
                          class="preview-column"
                        >
                          <el-tag size="small" :type="getColumnTagType(col.type)">
                            {{ getColumnTypeName(col.type) }}
                          </el-tag>
                          <span class="column-name">{{ col.label }}</span>
                          <el-button
                            type="danger"
                            link
                            size="small"
                            @click.stop="removeDynamicFormColumn(col, element)"
                          >
                            <el-icon><Delete /></el-icon>
                          </el-button>
                        </div>
                      </template>
                      <div v-else class="empty-columns">
                        <el-empty description="暂无列配置" />
                      </div>
                    </div>
                  </div>
                  
                  <!-- 拖拽区域 -->
                  <div class="dynamic-form-drop">
                    <div class="drop-header">
                      <span class="drop-title">拖拽添加列</span>
                    </div>
                    <draggable
                      class="dynamic-form-columns"
                      :list="element.options.columns"
                      :group="{
                        name: 'form',
                        put: function(to, from) {
                          // 检查是否从左侧组件列表拖入
                          return from.el.className.includes('left-aside') || from.el.className.includes('container');
                        }
                      }"
                      item-key="prop"
                      animation="300"
                      :sort="false"
                      :move="checkMove"
                      @add="(e) => handleDynamicFormAdd(e, element)"
                      @change="(e) => handleDynamicFormChange(e, element)"
                      @start="handleDragStart"
                      @end="handleDragEnd"
                    >
                      <template #item="{ element: column }">
                        <div class="dynamic-form-column-item">
                          <span>{{ column.label }}</span>
                        </div>
                      </template>
                      <template #footer>
                        <div class="dynamic-form-placeholder">
                          <el-icon><Plus /></el-icon>
                          <span>拖拽组件到这里添加列</span>
                        </div>
                      </template>
                    </draggable>
                  </div>
                </div>
              </div>
            </template>
            <template v-else>
              <element-comps :element="element" />
            </template>
          </div>
        </div>
      </template>
      <template #footer v-if="newList.length === 0">
        <div class="empty-content">
          <el-empty description="点击或拖拽左侧控件至此处">
            <template #image>
              <div class="empty-icon">
                <el-icon><Plus /></el-icon>
              </div>
            </template>
            <template #description>
              <div class="empty-text">
                <p class="primary-text">开始设计您的表单</p>
                <p class="secondary-text">从左侧拖拽组件或点击添加</p>
              </div>
            </template>
          </el-empty>
        </div>
      </template>
    </draggable>
  </div>
</template>

<style lang="scss" scoped>
.content-panel {
  flex: 1;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  
  // 栅格布局样式
  .grid-layout {
    margin: 16px 0;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 4px;
    
    .grid-col {
      padding: 0 12px;
      
      .form-item {
        margin-bottom: 18px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
  
  // 容器布局样式
  .container-layout {
    margin: 16px 0;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    
    .container-header {
      padding: 12px 16px;
      font-size: 14px;
      font-weight: 500;
      color: #303133;
      border-bottom: 1px solid #e4e7ed;
    }
    
    .container-body {
      padding: 16px;
      
      .form-item {
        margin-bottom: 18px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
  
  // 表单项样式
  .form-item {
    position: relative;
    padding: 12px;
    background: #f8f9fa;
    border-radius: 4px;
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    &.active {
      border: 1px dashed var(--el-color-primary);
    }
  }
}

.grid-container {
  width: 100%;
  padding: 8px;
  background: #fafafa;
  border-radius: 4px;

  .grid-col-container {
    min-height: 100px;
    padding: 8px;
    background: #fff;
    border: 1px dashed #e5e7eb;
    border-radius: 4px;
    
    &.sortable-ghost {
      background: var(--el-color-primary-light-9);
      border-color: var(--el-color-primary);
    }
    
    &:hover {
      border-color: var(--el-color-primary);
    }
  }

  .grid-item {
    margin: 8px 0;
    background: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 4px;
    transition: all 0.3s;
    
    &:hover {
      border-color: var(--el-color-primary);
    }
  }

  .grid-placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 16px;
    color: #909399;
    font-size: 13px;
    
    .el-icon {
      font-size: 16px;
    }
  }
}

// 拖拽时的样式优化
.sortable-ghost {
  position: relative;
  opacity: 0.5;
  background: #f0f7ff !important;
  border: 1px dashed #409EFF !important;
  height: 40px !important;
  padding: 8px !important;
  overflow: hidden;
  
  * {
    opacity: 0;
  }

  &::after {
    content: '放置到这里';
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    color: #409EFF;
    font-size: 12px;
  }
}

.sortable-drag {
  opacity: 0.9;
  background: #fff !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
  transform: rotate(1deg) !important;
  height: 40px !important;
}

// 响应式优化
@media screen and (max-width: 768px) {
  .content-panel {
    .content-header {
      padding: 12px 16px;

      .header-title {
        font-size: 14px;
      }
    }

    .container {
      padding: 12px;
    }

    .form-item {
      .item-content {
        padding: 8px 12px;

        :deep(.el-form-item) {
          .el-form-item__label {
            font-size: 12px;
          }

          .el-input__inner {
            font-size: 12px;
          }
        }
      }
    }
  }
}

// 优化特定组件样式
:deep(.component-radio-group) {
  .el-radio {
    margin-right: 12px;
    margin-bottom: 4px;
  }
}

:deep(.component-checkbox-group) {
  .el-checkbox {
    margin-right: 12px;
    margin-bottom: 4px;
  }
}

:deep(.component-select) {
  .el-select-dropdown__item {
    font-size: 13px;
    height: 32px;
    line-height: 32px;
  }
}

:deep(.component-date-picker) {
  .el-date-editor {
    width: 100%;
  }
}

.card-container {
  width: 100%;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  
  .card-header {
    padding: 12px 16px;
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .card-content {
    min-height: 100px;
    padding: 16px;
    
    &.sortable-ghost {
      background: var(--el-color-primary-light-9);
      border: 1px dashed var(--el-color-primary);
      border-radius: 4px;
    }
  }
  
  .card-item {
    margin: 8px 0;
    background: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 4px;
    transition: all 0.3s;
    
    &:hover {
      border-color: var(--el-color-primary);
    }
  }
  
  .card-placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 16px;
    color: #909399;
    font-size: 13px;
    border: 1px dashed #e5e7eb;
    border-radius: 4px;
    
    &:hover {
      border-color: var(--el-color-primary);
      color: var(--el-color-primary);
    }
    
    .el-icon {
      font-size: 16px;
    }
  }
}

.dynamic-form-container {
  width: 100%;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #fff;
  
  .dynamic-form-header {
    padding: 12px 16px;
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    border-bottom: 1px solid #e4e7ed;
  }
  
  .dynamic-form-content {
    padding: 16px;
    
    .dynamic-form-preview {
      margin-bottom: 16px;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      
      .preview-header {
        padding: 12px 16px;
        font-size: 14px;
        font-weight: 500;
        color: #303133;
        background: #f8f9fa;
        border-bottom: 1px solid #e4e7ed;
      }
      
      .preview-columns {
        padding: 16px;
        min-height: 100px;
        
        .preview-column {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 8px 12px;
          background: #f8f9fa;
          border: 1px solid #e4e7ed;
          border-radius: 4px;
          margin-bottom: 8px;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .column-name {
            flex: 1;
            font-size: 14px;
            color: #606266;
          }
          
          .el-button {
            padding: 4px;
          }
        }
        
        .empty-columns {
          display: flex;
          align-items: center;
          justify-content: center;
          height: 200px;
        }
      }
    }
    
    .dynamic-form-drop {
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      
      .drop-header {
        padding: 12px 16px;
        font-size: 14px;
        font-weight: 500;
        color: #303133;
        background: #f8f9fa;
        border-bottom: 1px solid #e4e7ed;
      }
      
      .dynamic-form-columns {
        min-height: 100px;
        padding: 16px;
        
        .dynamic-form-column-item {
          display: none;  // 隐藏实际的列项
        }
        
        &.sortable-ghost {
          background: var(--el-color-primary-light-9);
          border: 1px dashed var(--el-color-primary);
          border-radius: 4px;
        }
      }
    }
    
    .dynamic-form-placeholder {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      padding: 16px;
      color: #909399;
      font-size: 13px;
      border: 1px dashed #e5e7eb;
      border-radius: 4px;
      
      &:hover {
        border-color: var(--el-color-primary);
        color: var(--el-color-primary);
      }
      
      .el-icon {
        font-size: 16px;
      }
    }
  }
  
  &:hover {
    border-color: var(--el-color-primary);
  }
}
</style>

<script setup>
import { ref, watch } from "vue";
import { useStore } from "vuex";
import draggable from "vuedraggable";
import { Delete, DArrowRight, Plus, ArrowUp, ArrowDown, CopyDocument } from '@element-plus/icons-vue';
import ElementComps from "./ElementComps.vue";
//import { useFormStore } from '@/stores/form'
import { nanoid } from "nanoid";
//import MoveIcon from '../icons/move.vue'
//import DeleteIcon from '../icons/delete.vue'

/* ts类型定义区域 */

/* 定义数据区域 */
const props = defineProps({
  list: {
    type: Array,
    default: () => [],
  },
});

const newList = ref([]);
const currentIndex = ref(0);
const showOperate = ref(false);
const selectFormItem = ref(null);
const emits = defineEmits(["currentItemClick"]);
const store = useStore();
//   const formStore = useFormStore()

/* 事件处理区域 */

// 当前点击的组件
const handleClick = (element, index) => {
store.dispatch("form/selectFormItem", element);
  console.log("element", element);
  currentIndex.value = index;
  showOperate.value = true;
  emits("currentItemClick", element);
};

// 监听组件的移动/添加
const handleDragChange = (e) => {
  console.log("e", e);

  if (e.added) {
    // 组件添加
    const element = e.added.element;
    const index = e.added.newIndex;
    element.id = getFormId(); // 使每个组件的字段名都不一样，避免同个组件字段名一样
    handleClick(element, index);
    return;
  }

  if (e.moved) {
    // 组件移动
    const element = e.moved.element;
    const index = e.moved.newIndex;
    handleClick(element, index);
    return;
  }
};

// 移出组件
const removeAt = (index) => {
  newList.value.splice(index, 1);
  emits("currentItemClick", {});
  store.dispatch("form/updateConfig", newList.value);
  //store.commit("updateConfig", newList.value);
  // formStore.updateConfig(newList.value)
};

// 拖拽放下触发
const dragDown = () => {
  console.log("拖拽放下触发", JSON.stringify(newList.value));
  // store.commit("updateConfig", newList.value);
  store.dispatch("form/updateConfig", newList.value);
};

// 拖拽结束
const dragEnd = () => {
  showOperate.value = true;
};


const getSelectedClass = (cp) =>{
      return selectFormItem.value && selectFormItem.value.id === cp.id ?
          'border-left: 4px solid #409eff':''
}

/**
 * 获取表单id
 */
 const getFormId = () => {
  return `form_${new Date().getTime().toString().substring(5)}${Math.round(
    Math.random() * 9000 + 1000
  )}`;
}

/* 监听 */
watch(
  () => store.state.form.config,
  (newVal) => {
    newList.value = newVal;
    console.log("newVal", newVal);
    //   formStore.updateConfig(newVal)
  }
);


watch(
  () => store.state.form.selectFormItem,
  (newVal) => {
    selectFormItem.value = newVal;
    console.log("selectFormItem", newVal);
    //   formStore.updateConfig(newVal)
  }
);

watch(props.list, (newVal) => {
  store.dispatch("form/updateConfig", newVal);
});

watch(
  () => store.state.form.tempConfig,
  (newVal) => {
    newVal.forEach((item) => {
      newList.value.forEach((iten) => {
        if (item.id === iten.id) {
          iten.hasError = item.hasError;
        }
      });
    });

    // newList.value = newVal
  }
);

watch(
  () => store.state.form.currentIndex,
  (newVal) => {
    const element = store.state.form.config[newVal];
    handleClick(element, newVal);
  }
);

// 移动组件位置
const moveItem = (index, direction) => {
  if (direction === 'up' && index > 0) {
    [newList.value[index], newList.value[index - 1]] = [newList.value[index - 1], newList.value[index]]
  } else if (direction === 'down' && index < newList.value.length - 1) {
    [newList.value[index], newList.value[index + 1]] = [newList.value[index + 1], newList.value[index]]
  }
}

// 复制组件
const copyItem = (element) => {
  const copy = JSON.parse(JSON.stringify(element))
  copy.id = nanoid()
  newList.value.push(copy)
  ElMessage.success('复制成功')
}

// 处理栅格列的组件添加
const handleColAdd = (e, colIndex, gridElement) => {
  if (e.added) {
    const element = e.added.element;
    const index = e.added.newIndex;
    element.id = getFormId();
    handleClick(element, index);
    // 更新 store 中的配置
    store.dispatch("form/updateConfig", newList.value);
  }
};

// 处理栅格列的组件变化
const handleColChange = (e, colIndex, gridElement) => {
  if (e.added || e.moved || e.removed) {
    // 更新 store 中的配置
    store.dispatch("form/updateConfig", newList.value);
  }
};

// 处理卡片布局的组件添加
const handleCardAdd = (e, cardElement) => {
  if (e.added) {
    const element = e.added.element;
    const index = e.added.newIndex;
    element.id = getFormId();
    handleClick(element, index);
    // 更新 store 中的配置
    store.dispatch("form/updateConfig", newList.value);
  }
};

// 处理卡片布局的组件变化
const handleCardChange = (e, cardElement) => {
  if (e.added || e.moved || e.removed) {
    // 更新 store 中的配置
    store.dispatch("form/updateConfig", newList.value);
  }
};

// 处理动态表单的组件添加
const handleDynamicFormAdd = (e, formElement) => {
  if (e.added) {
    const element = e.added.element;
    console.log('添加的元素:', element);
    
    // 只允许特定类型的组件作为列
    const allowedTypes = ['single-input', 'number', 'select', 'date', 'radio', 'checkbox'];
    if (!allowedTypes.includes(element.type)) {
      // 如果不是允许的类型，移除该组件
      formElement.options.columns.splice(e.added.newIndex, 1);
      ElMessage.warning('该组件类型不支持作为动态表单的列');
      return;
    }

    // 根据拖入的组件类型创建对应的列配置
    const column = {
      type: element.type,
      label: element.name,
      prop: `field_${nanoid(6)}`,
      placeholder: element.options?.placeholder || '请输入',
      width: '200px',
      defaultValue: element.options?.defaultValue,
      rules: []
    };
    
    // 处理不同类型组件的特殊配置
    if (['select', 'radio', 'checkbox'].includes(element.type)) {
      column.options = element.options.selectOptions || [];
    } else if (element.type === 'number') {
      column.min = element.options?.minValue;
      column.max = element.options?.maxValue;
    } else if (element.type === 'date') {
      column.format = element.options?.format;
      column.valueFormat = element.options?.valueFormat;
    }
    
    // 替换添加的组件为列配置
    e.added.element = column;
    
    // 初始化默认行数据
    if (formElement.options.defaultValue.length > 0) {
      formElement.options.defaultValue.forEach(row => {
        row[column.prop] = column.defaultValue;
      });
    }
    
    // 更新 store 中的配置
    store.dispatch("form/updateConfig", newList.value);
    ElMessage.success('添加列成功');
  }
};

// 处理动态表单列的变化
const handleDynamicFormChange = (e, formElement) => {
  if (e.added || e.moved || e.removed) {
    // 更新 store 中的配置
    store.dispatch("form/updateConfig", newList.value);
  }
};

// 删除动态表单列
const removeDynamicFormColumn = (column, formElement) => {
  const index = formElement.options.columns.findIndex(col => col.prop === column.prop);
  if (index > -1) {
    formElement.options.columns.splice(index, 1);
    store.dispatch("form/updateConfig", newList.value);
  }
};

// 获取列类型对应的标签类型
const getColumnTagType = (type) => {
  const typeMap = {
    'single-input': '',
    'number': 'success',
    'select': 'warning',
    'date': 'info',
    'radio': 'danger',
    'checkbox': 'danger'
  };
  return typeMap[type] || '';
};

// 获取列类型对应的中文名称
const getColumnTypeName = (type) => {
  const typeMap = {
    'single-input': '文本',
    'number': '数字',
    'select': '下拉选择',
    'date': '日期',
    'radio': '单选',
    'checkbox': '多选'
  };
  return typeMap[type] || type;
};

// 检查是否允许移动
const checkMove = (evt) => {
  const { draggedContext, relatedContext } = evt;
  const { element: draggedElement } = draggedContext;
  
  // 只允许特定类型的组件
  const allowedTypes = ['single-input', 'number', 'select', 'date', 'radio', 'checkbox'];
  
  // 如果是从左侧拖入的组件
  if (draggedElement.type) {
    return allowedTypes.includes(draggedElement.type);
  }
  
  return false;
};

// 处理拖拽开始
const handleDragStart = (e) => {
  // 可以添加一些拖拽开始时的逻辑
  console.log('开始拖拽', e);
};

// 处理拖拽结束
const handleDragEnd = (e) => {
  // 可以添加一些拖拽结束时的逻辑
  console.log('结束拖拽', e);
};

/* 生命周期 */
</script>
  